package com.mach.platform.controller;

import com.alibaba.fastjson.JSON;
import com.mach.platform.domain.Response;
import com.mach.platform.domain.SysImg;
import com.mach.platform.service.SysImgServiceImpl;
import com.mach.platform.utils.UUIDUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 * @Description:
 * @Package: com.mach.platform.controller
 * @time 2018/8/20 0020 12:01
 */

@PreAuthorize(value = "hasAnyRole('ROLE_SUPER_ADMIN','ROLE_RENAULT','ROLE_DEMO')")
@RequestMapping("sysimg")
@RestController
public class SysImgCtrl extends BaseCtrl<SysImg> {

	@Autowired
	private SysImgServiceImpl sysImgService;

	/**
	 * -- @GetMapping(value = "/info/{id}")
	 * -- @ApiOperation(value = "单个实体信息", notes = "接口备注：无", produces = "application/json")
	 * 单个数据 的接口
	 * -- @PathVariable(value = "id", required = true) Long id
	 *
	 * @param id 数据的id
	 * @return Response
	 */
	@GetMapping(value = "/info/{id}")
	@Override
	public Response info (@PathVariable("id") Long id) {
		SysImg info = sysImgService.info(id);
		return Response.ok(info);
	}

	/**
	 * --	@ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
	 * -- @GetMapping(value = "/list")
	 * 获取列表数据
	 * -- @PageableDefault(size = 25) Pageable pageable
	 * -- @RequestParam Map params
	 *
	 * @param pageable 分页参数
	 * @param params   其他参数
	 *
	 *
	 * @return Response
	 */
	@PostMapping("list")
	@Override
	public Response list (@PageableDefault Pageable pageable,@RequestParam Map params) {

		Page<SysImg> sysImgs = sysImgService.list(pageable, params);

		return Response.ok(sysImgs);
	}

	/**
	 * -- @DeleteMapping("/del")
	 * -- @ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
	 * 删除数据
	 * -- @RequestBody Long[] ids
	 *
	 * @param ids id的集合
	 * @return Response
	 */
	@DeleteMapping("/del")
	@Override
	public Response delete (@RequestBody Long[] ids) {
		int delete = sysImgService.delete(ids);
		return Response.ok(delete);
	}

	/**
	 * --@PostMapping("/save")
	 * --	@ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
	 * 保存一个 对象
	 * --@RequestBody T t
	 *
	 * @param sysImg 保存的实体
	 * @return Response
	 */
//	@PreAuthorize("hasAuthority('ROLE_SUPER_ADMIN', 'ROLE_DEMO')")
	@PostMapping("save")
	@Override
	public Response save (@RequestBody SysImg sysImg) {
		SysImg save = sysImgService.save(sysImg);
		return Response.ok(save);
	}

	/**
	 * --@PutMapping("/upd")
	 * --	@ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
	 * 更新一个对象
	 * --@RequestBody T t
	 *
	 * @param sysImg 更新的实体
	 * @return Response
	 */
//	@PreAuthorize("hasAuthority('ROLE_SUPER_ADMIN')")
	@PutMapping("upd")
	@Override
	public Response update (@RequestBody SysImg sysImg) {

		SysImg update = sysImgService.update(sysImg);
		return Response.ok(update);
	}

	/**
	 * 上传 图片并且保存 系统图
	 * @param sysImg
	 * @param file
	 * @return
	 */
	@PostMapping("newPic")
	public Response newPic(@RequestParam("sysImg") String sysImg,@RequestParam("img") MultipartFile file){

		// 获取保存的数据
		SysImg parseObject = JSON.parseObject(sysImg, SysImg.class);
		File finalSave = null;
		String oldUrl = "";
		if (parseObject.getId() != null) {
			SysImg oldOne = sysImgService.info(parseObject.getId());
			oldUrl = oldOne.getImgUrl();
		}

		try {

			File targetPath = new File(getPicSavePath(), "/pic");
			if (!targetPath.exists()) {
				targetPath.mkdirs();
			}

			String picName = UUIDUtils.generateUUID() + ".png";

			finalSave = new File(targetPath.getPath() + File.separator + picName);

			// 保存图片
			FileUtils.copyInputStreamToFile(file.getInputStream(), finalSave);

			parseObject.setImgUrl(finalSave.getAbsolutePath());

			if (parseObject.getId() == null) {
				// 新增操作
				sysImgService.save(parseObject);
			} else {
				// 更新操作
				sysImgService.update(parseObject);
				// 删除旧的图片
				File fileOld = new File(oldUrl);
				if (fileOld.exists()) {
					FileUtils.forceDelete(fileOld);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return Response.ok("保存成功！");
	}

		/**
		 * 获取 jar包所在 目录路径
		 * @return
		 */
		public String getPicSavePath () {
			ApplicationHome home = new ApplicationHome(getClass());
			File jarFile = home.getSource();
			return jarFile.getParentFile().getParentFile().getAbsolutePath();
		}
}
